using MicroMsg.Common.Algorithm;
using MicroMsg.Common.Event;
using MicroMsg.Common.Timer;
using MicroMsg.Common.Utils;
using MicroMsg.Manager;
using MicroMsg.Storage;
using System;
using System.Collections.Generic;
namespace MicroMsg.Scene.Video
{
	public class UploadVideoService
	{
		private const string TAG = "UploadVideoService";
		private const int MAX_RUNNING = 5;
		private static TimerObject mTimerObject;
		private EventWatcher mWatcherToCleanStatus;
		public UploadVideoService()
		{
			this.mWatcherToCleanStatus = new EventWatcher(this, null, new EventHandlerDelegate(UploadVideoService.onHandlerToCleanStatus));
			EventCenter.registerEventWatcher(EventConst.ON_NETSCENE_SYNC, this.mWatcherToCleanStatus);
		}
		private static void onHandlerToCleanStatus(EventWatcher watcher, BaseEventArgs evtArgs)
		{
			NetSceneSyncResult netSceneSyncResult = evtArgs.mObject as NetSceneSyncResult;
			if (netSceneSyncResult != null && netSceneSyncResult.syncStatus == SyncStatus.syncEnd && netSceneSyncResult.syncCount == 0)
			{
				UploadVideoService.cleanSendingStatus();
				return;
			}
		}
		public bool doSence(string toUserName, string videoFile, string thumbFile, int playLength)
		{
			string hashString = MD5Core.GetHashString(toUserName + Util.getNowMilliseconds());
			UploadVideoContext uploadVideoContext = UploadVideoContext.createByClientMsgID(hashString);
			if (uploadVideoContext == null)
			{
				Log.smethod_1("UploadVideoService", "create upload video context failed. ");
				return false;
			}
			Log.smethod_4("UploadVideoService", "cmd to scene begin, toUserName = " + toUserName + " , clientMsgId = " + hashString);
			uploadVideoContext.mVideoTrans.strToUserName = toUserName;
			uploadVideoContext.mVideoTrans.strFromUserName = AccountMgr.getCurAccount().strUsrName;
			uploadVideoContext.mVideoTrans.strThumbnail = thumbFile;
			uploadVideoContext.mVideoTrans.strImagePath = videoFile;
			uploadVideoContext.mVideoTrans.nDuration = playLength;
			uploadVideoContext.mStatus = 0;
			uploadVideoContext.preProcessVideoFile(thumbFile, videoFile);
			if (!uploadVideoContext.initThumbFileStream())
			{
				Log.smethod_1("UploadVideoService", "failed to load thumb file. ");
				return false;
			}
			if (!uploadVideoContext.initVideoFileStream())
			{
				Log.smethod_1("UploadVideoService", "failed to load video file. ");
				return false;
			}
			uploadVideoContext.addVoiceChatMsg();
			UploadVideoContextMgr.getInstance().putToHead(uploadVideoContext);
			UploadVideoService.checkReadyContextDispatcher();
			return true;
		}
		public bool doSceneResume(string clientMsgId)
		{
			Log.smethod_4("UploadVideoService", "cmd to scene resume,  clientMsgId = " + clientMsgId);
			if (UploadVideoContextMgr.getInstance().findByClientMsgID(clientMsgId) != null)
			{
				Log.smethod_1("UploadVideoService", "already running,clean first. " + clientMsgId);
				UploadVideoContextMgr.getInstance().clearnFinishedContext();
				if (UploadVideoContextMgr.getInstance().findByClientMsgID(clientMsgId) != null)
				{
					Log.smethod_1("UploadVideoService", "already running, ignored! clientMsgId = " + clientMsgId);
					return false;
				}
			}
			if (!UploadVideoService.resumeByClientMsgID(clientMsgId))
			{
				return false;
			}
			UploadVideoService.checkReadyContextDispatcher();
			return true;
		}
		public bool doCancelScene(string clientMsgId)
		{
			UploadVideoContext uploadVideoContext = UploadVideoContextMgr.getInstance().findByClientMsgID(clientMsgId);
			if (uploadVideoContext == null)
			{
				Log.smethod_1("UploadVideoService", "not found clientMsgId= " + clientMsgId);
				return false;
			}
			if (uploadVideoContext.mStatus != 5)
			{
				if (uploadVideoContext.mStatus != 4)
				{
					if (uploadVideoContext.mScene == null)
					{
						Log.smethod_1("UploadVideoService", "task not runing, clientMsgId= " + clientMsgId);
						uploadVideoContext.mStatus = 4;
						uploadVideoContext.updateContext();
						uploadVideoContext.onFinished();
						return false;
					}
					uploadVideoContext.mScene.doCancel();
					return true;
				}
			}
			Log.smethod_1("UploadVideoService", "wait to clean , clientMsgId= " + clientMsgId);
			return false;
		}
		public UploadVideoContext.ProgressInfo getProgress(string clientMsgSvrId)
		{
			MsgTrans byClientMsgID = StorageMgr.msgImg.getByClientMsgID(clientMsgSvrId);
			if (byClientMsgID != null)
			{
				UploadVideoContext.ProgressInfo progressInfo = new UploadVideoContext.ProgressInfo();
				progressInfo.totalLength = byClientMsgID.nTotalDataLen + byClientMsgID.nRecordLength;
				progressInfo.sentLength = byClientMsgID.nTransDataLen + byClientMsgID.nEndFlag;
				progressInfo.clientMsgId = byClientMsgID.strClientMsgId;
				progressInfo.status = UploadVideoContext.convertStatus(byClientMsgID.nStatus);
				progressInfo.printInfo();
				return progressInfo;
			}
			return null;
		}
		private static void checkReadyContextDispatcher()
		{
			if (UploadVideoService.mTimerObject == null)
			{
				Log.smethod_5("UploadVideoService", "upload video service dispatcher startup. ");
				UploadVideoService.mTimerObject = TimerService.addTimer(8, new EventHandler(UploadVideoService.onVideoContextDispatcher), 1, -1);
				UploadVideoService.mTimerObject.start();
			}
		}
		public static void onVideoContextDispatcher(object sender, EventArgs e)
		{
			UploadVideoContextMgr.getInstance().clearnFinishedContext();
			if (UploadVideoContextMgr.getInstance().getCount() <= 0)
			{
				UploadVideoService.closeDispatcherTimer();
				return;
			}
			if (UploadVideoContextMgr.getInstance().countRunningContext() >= 5)
			{
				return;
			}
			UploadVideoContext firstContextNeedHandle = UploadVideoContextMgr.getInstance().getFirstContextNeedHandle();
			if (firstContextNeedHandle == null)
			{
				return;
			}
			Log.smethod_4("UploadVideoService", "new task startup, clientmsgid = " + firstContextNeedHandle.mVideoTrans.strClientMsgId);
			NetSceneUploadVideo netSceneUploadVideo = new NetSceneUploadVideo();
			netSceneUploadVideo.doScene(firstContextNeedHandle);
		}
		private static void closeDispatcherTimer()
		{
			Log.smethod_4("UploadVideoService", "all ready, close dispatcher timer. ");
			if (UploadVideoService.mTimerObject != null)
			{
				UploadVideoService.mTimerObject.stop();
				UploadVideoService.mTimerObject = null;
			}
		}
		public static bool resumeByClientMsgID(string clientMsgID)
		{
			MsgTrans byClientMsgID = StorageMgr.msgVideo.getByClientMsgID(clientMsgID);
			if (byClientMsgID == null)
			{
				Log.smethod_1("UploadVideoService", "not found task ,clientmsgid =  " + clientMsgID);
				return false;
			}
			if (byClientMsgID.nStatus == 5)
			{
				return false;
			}
			Log.smethod_4("UploadVideoService", "resuming.... " + clientMsgID);
			UploadVideoContext uploadVideoContext = UploadVideoContext.createByMsgTrans(byClientMsgID);
			if (!uploadVideoContext.loadFromMsgTrans())
			{
				Log.smethod_1("UploadVideoService", "Failed to load video data,  " + byClientMsgID.strClientMsgId);
				return false;
			}
			Log.smethod_5("UploadVideoService", "load video file success, put task to head. ");
			UploadVideoContextMgr.getInstance().putToHead(uploadVideoContext);
			return true;
		}
		public static void cleanSendingStatus()
		{
			List<ChatMsg> list = StorageMgr.chatMsg.searhCacheMsg(43, 0, 1);
			if (list != null && list.get_Count() > 0)
			{
				using (List<ChatMsg>.Enumerator enumerator = list.GetEnumerator())
				{
					while (enumerator.MoveNext())
					{
						ChatMsg current = enumerator.get_Current();
						Log.smethod_4("UploadVideoService", "Failed to clean status-sending , " + current.strClientMsgId);
						current.nStatus = 1;
					}
				}
				StorageMgr.chatMsg.updateMsgList(list);
				return;
			}
		}
	}
}
